package com.example.demo.controller;

import com.example.demo.utility.RedisUtil;
import com.example.demo.mapper.UserMapper;
import com.example.demo.pojo.User;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * 复述,控制器
 *
 * @author yzh
 * @date 2022/09/01
 */
@Slf4j
@RestController
@RequestMapping("/redis")
public class RedisController {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ThymeleafViewResolver thymeleafViewResolver;
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("test")

    public Object test() {
        redisUtil.set("r", "aaaaaa");
        return redisUtil.get("r");
    }

    /**
     * test2
     * 测试将查询的数据存到redis
     */
    @Test
    public void test2() {
        User tom = userMapper.selectByName("Tom");
        System.out.println(tom);
        /*redisUtil.set("user",tom);*/
        System.out.println(redisUtil.get("user"));
    }

    /**
     * test3
     * 将页面进行缓存
     *
     * @param model    模型
     * @param request  请求
     * @param response 响应
     * @return {@link String}
     */
    @ResponseBody
    @RequestMapping(value = "test3", produces = "text/html;charset=utf-8")
    public String test3(Model model, HttpServletRequest request, HttpServletResponse response) {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String html = (String) valueOperations.get("login.html");
        if (!StringUtil.isNullOrEmpty(html)) {
            return html;
        }
        WebContext webContext = new WebContext(request, response, request.getServletContext(), request.getLocale(), model.asMap());
        html = thymeleafViewResolver.getTemplateEngine().process("登录模板", webContext);
        valueOperations.set("login.html", html, 1, TimeUnit.MINUTES);
        return html;
    }

    @RequestMapping("test4")
    public String test4(Model model) {
        model.addAttribute("username", "赵六");
        return "登录模板";
    }
}
